import { getListFiles, getImgUrl } from '@/utils/files';
import { upFileMulti } from '@/utils/files';
import { commonRequest } from '@/api/commonlist';
import { getAppId } from '@/utils/local';

const isDef = (v) => {
  return v !== undefined && v !== null;
};

export const isArray = data => Array.isArray(data);

export const isPromise = (val) => {
  return (
    isDef(val) &&
		typeof val.then === 'function' &&
		typeof val.catch === 'function'
  );
};

// 服务 uploadFilesArr
const getLocalFiles = arr => {
  return arr.reduce((p, c) => {
    if (c.myValue) {
      p.push(...c.myValue);
    }
    return p;
  }, [])
    .map(o => o.file);
};

// 服务 getServerFiles
const getFilePage = (item, guid, type) => {
  item.myLoading = true;
  return getListFiles({
    guid
  }).then(res => {
    const { success, data } = res;
    setTimeout(async() => {
      item.myLoading = false;

      if (success) {
        if (type === 'file') {
          data.forEach(o => {
            o.name = o.originName;
          });
          item.myValue = data.map(file => ({ file }));
        } else if (type === 'pic') {
          const imgs = [];
          for (let i = 0; i < data.length; i++) {
            const { id, originName: fileName } = data[i];
            await getImgUrl({ id, fileName }).then(url => {
              imgs.push({ img: url });
            });
          }

          item.myValue = imgs;
        }
      }
    }, 500);

    return Promise.resolve(res);
  });
};

// 上传文件
export const uploadFiles = (files, guid) => {
  const form = new FormData();
  form.append('guid', guid);
  files.map(file => {
    form.append('files', file);
  });
  return upFileMulti(form);
};

// 上传模板库内选中的文件
export const uploadFilesArr = (data) => {
  const {
    imgsItem, // []
    filesItem, // []
    guid // string
  } = data;

  const files = getLocalFiles(filesItem);
  const imgs = getLocalFiles(imgsItem);
  const waiting = [];

  if (files.length) {
    waiting.push(uploadFiles(files, guid + '_1'));
  }

  if (imgs.length) {
    waiting.push(uploadFiles(imgs, guid + '_2'));
  }

  if (waiting.length) {
    return Promise.allSettled(waiting);
  }
};

// 判断是否有上传的文件
export const getServerFiles = (renderList, formGuid, componentType) => {
  const filesItem = renderList.filter(item => item.componentType === componentType.chooseFile);
  const imgsItem = renderList.filter(item => item.componentType === componentType.chooseImage);
  const fLen = filesItem.length;
  const iLen = imgsItem.length;

  const waiting = [];

  if (fLen || iLen) {
    if (fLen) {
      // 选择附件、图片最多存在一个
      waiting.push(
        getFilePage(filesItem[0], formGuid + '_1', 'file')
      );
    }

    if (iLen) {
      waiting.push(
        getFilePage(imgsItem[0], formGuid + '_2', 'pic')
      );
    }
  }
  return Promise.allSettled(waiting);
};

// 获取模板库的列
export const getModelList = (name) => {
  const requestData = {
    pageSize: 999,
    pageIndex: 0,
    appId: getAppId(),
    name
  };

  return commonRequest(requestData, '/modelForm/list').then(res => {
    const { success, data } = res;
    if (success) {
      if (isArray(data) && data.length) {
        return data;
      }
    }

    return Promise.reject(res || '获取模板库失败');
  });
};

// 获取模板库的的表单样式
export const getModelStyleData = (name) => {
  return getModelList(name).then(data => {
    if (data) {
      const modelData = data[0];
      const { tableInfo: { children }} = modelData;

      // 模板内容表头
      const modelContent = children.find(o => o.tableName.includes('模板内容'));

      // 审批内容表头
      const approveContent = children.find(o => o.tableName.includes('审批内容'));

      const isModelForm = modelContent && modelContent.isForm === 1 || false;
      const isApproveForm = approveContent && approveContent.isForm === 1 || false;

      return Promise.resolve({
        modelContent,
        approveContent,
        isModelForm,
        isApproveForm
      });
    }
  });
};

export const filterIsForm = (headers, isNeedCopy) => {
  // isCopy
  const normal = [];
  const copy = [];

  headers.map(item => {
    if (item.isCopy === 1 && isNeedCopy) {
      item.myCopy = true;
      copy.push(item);
    }
    normal.push(item);
  });

  return {
    headers: normal,
    copy
  };
};

// 收集copy的每行的数据
export const collectCopyRow = (headers) => {
  const map = new Map();

  headers.forEach(header => {
    const { myCopyIndex } = header;
    if (myCopyIndex) {
      const row = map.get(myCopyIndex);
      if (!row) {
        map.set(myCopyIndex, [header]);
      } else {
        row.push(header);
      }
    }
  });

  return [...map.values()];
};
